/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: PeriodController.java 47 2012-09-20 06:31:35Z zhuxiaopeng $
 * $Revision: 47 $
 * $Date: 2012-09-20 14:31:35 +0800 (四, 2012-09-20) $
 * $Author: zhuxiaopeng $
 */
package daily.web.period;

import static zhu.framework.web.WebUtility.*;

import java.util.*;

import javax.ejb.*;
import javax.enterprise.context.*;
import javax.inject.*;

import zhu.framework.service.*;
import zhu.framework.web.*;
import zhu.framework.web.jsf.*;
import daily.entity.*;
import daily.service.*;
import daily.util.*;
import daily.web.SessionBean;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 47 $ - $Date: 2012-09-20 14:31:35 +0800 (四, 2012-09-20) $
 */
@Named
@RequestScoped
public class PeriodController extends ConversationalController {
	private enum ActionOutCome {
		EDIT, SAVE, CANCEL
	}

	public boolean isNextDisabled() {
		return DateUtils.compareIgnoreTime(periodConversation.getDateRange().getDate(), new Date()) >= 0;
	}

	public boolean isCurrentDisabled() {
		return DateUtils.compareIgnoreTime(periodConversation.getDateRange().getDate(), new Date()) == 0;
	}

	public void current() {
		periodConversation.current();
	}

	public void prior() {
		periodConversation.prior();
	}

	public void next() {
		periodConversation.next();
	}

	public boolean isTodayBefore(final Date date) {
		return DateUtils.compareIgnoreTime(date, new Date()) <= 0;
	}

	public List<DailyData> getDailyList(final Staff staff) {
		Map<Staff, List<DailyData>> dailyMap = periodConversation.getDailyMap();
		if (dailyMap == null) {
			final DateRange dateRange = periodConversation.getDateRange();
			final Date startDate = dateRange.getPeriodType().getStartDate(dateRange.getDate());
			final Date endDate = dateRange.getPeriodType().getEndDate(dateRange.getDate());
			dailyMap = dailyService.getDailyByPeriod(sessionBean.getLoginStaff(), sessionBean.getStaffList(), startDate, endDate);
			periodConversation.setDailyMap(dailyMap);
		}
		return dailyMap.get(staff);
	}

	public String editDaily() {
		return ActionOutCome.EDIT.toString();
	}

	public String saveDaily() {
		try {
			dailyService.saveDaily(periodConversation.getSelectDaily());
		} catch (final BusinessException e) {
			getWebRequestContext().addMessages(WebMessage.valueOf(e.getMessages()));
			return null;
		}
		periodConversation.setDailyMap(null);
		return ActionOutCome.SAVE.toString();
	}

	public String cancel() {
		return ActionOutCome.CANCEL.toString();
	}

	@EJB
	private DailyServiceImpl dailyService;

	@Inject
	private PeriodConversation periodConversation;

	@Inject
	private SessionBean sessionBean;

}
